<template>
  <div>
    <h1>文章管理</h1>
    
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :rules="searchRules" ref="searchFormRef" label-width="100px" :inline="true">
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="searchForm.title" placeholder="请输入文章标题" style="width: 200px;" />
        </el-form-item>     

        <el-form-item label="文章类型">
          <el-select v-model="searchForm.type" placeholder="请选择文章类型" style="width: 150px;">
            <el-option label="全部" value="" />
            <el-option label="纯文章" value="text" />
            <el-option label="音频文章" value="audio" />
            <el-option label="视频文章" value="video" />
          </el-select>
        </el-form-item>

        <el-form-item label="操作人">
          <el-input v-model="searchForm.operator" placeholder="请输入操作人" style="width: 150px;" />
        </el-form-item>
        
        <el-form-item label="创建时间" prop="createTimeRange">
          <el-date-picker
            v-model="searchForm.createTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px;"
          />
        </el-form-item>
        
        <el-form-item label="更新时间" prop="updateTimeRange">
          <el-date-picker
            v-model="searchForm.updateTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px;"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增文章</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 文章表格 -->
    <el-table :data="articles" border style="width: 100%; margin-top: 20px;">
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="title" label="标题" width="200" show-overflow-tooltip />
      <el-table-column prop="summary" label="简介" width="250" show-overflow-tooltip />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.type)">
            {{ getTypeText(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="audioUrl" label="音频链接" width="150">
        <template #default="scope">
          <span v-if="scope.row.audioUrl">
            <el-link type="primary" @click="previewMedia(scope.row.audioUrl, 'audio')">
              <el-icon><VideoPlay /></el-icon>
              播放音频
            </el-link>
          </span>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>
      <el-table-column prop="videoUrl" label="视频链接" width="150">
        <template #default="scope">
          <span v-if="scope.row.videoUrl">
            <el-link type="primary" @click="previewMedia(scope.row.videoUrl, 'video')">
              <el-icon><VideoPlay /></el-icon>
              播放视频
            </el-link>
          </span>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>
      <el-table-column prop="operator" label="操作人" width="120" />
      <el-table-column prop="updater" label="更新人" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column prop="updateTime" label="更新时间" width="160" />
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="viewDetail(scope.row)">
            详情
          </el-button>
          <el-button type="warning" size="small" @click="editArticle(scope.row)">
            编辑
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="deleteArticle(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; text-align: right;"
    />
    
    <!-- 删除确认对话框 -->
    <DialogConfirm 
      v-model="deleteDialogVisible"
      :message="deleteDialogMessage"
      @confirm="handleDeleteConfirm"
      @cancel="handleDeleteCancel"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
// import api from '@/../api/api.js'
// import request from '@/../api/request.js'
import DialogConfirm from '@/component/DialogConfirm.vue'

const router = useRouter()

// 表单引用
const searchFormRef = ref()

// 搜索表单
const searchForm = reactive({
  title: '',
  type: '',
  operator: '',
  createTimeRange: [],
  updateTimeRange: []
})

// 删除确认对话框相关
const deleteDialogVisible = ref(false)
const deleteDialogMessage = ref('')
const currentDeleteRow = ref(null)

// 自定义验证函数
const validateTimeRange = (rule, value, callback) => {
  if (!value || value.length !== 2) {
    callback() // 时间范围可以为空
  } else {
    const [startTime, endTime] = value
    if (new Date(startTime) >= new Date(endTime)) {
      callback(new Error('开始时间必须小于结束时间'))
    } else {
      callback()
    }
  }
}

// 搜索表单验证规则
const searchRules = {
  createTimeRange: [{ validator: validateTimeRange, trigger: 'change' }],
  updateTimeRange: [{ validator: validateTimeRange, trigger: 'change' }]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 文章列表数据
const articles = ref([])

// 模拟文章数据
const mockData = [
  {
    id: 1,
    title: '《Vue 3 组合式API详解》',
    summary: '本文详细介绍了Vue 3的组合式API的使用方法和最佳实践，包括reactive、ref、computed等核心概念的深入解析。',
    type: 'text',
    audioUrl: '',
    videoUrl: '',
    operator: '张三',
    updater: '李四',
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-20 14:25:00'
  },
  {
    id: 2,
    title: '《JavaScript异步编程音频教程》',
    summary: '通过音频形式讲解JavaScript异步编程的核心概念，包括Promise、async/await、事件循环等重要知识点。',
    type: 'audio',
    audioUrl: 'https://example.com/audio/js-async.mp3',
    videoUrl: '',
    operator: '王五',
    updater: '王五',
    createTime: '2024-01-18 09:15:00',
    updateTime: '2024-01-18 09:15:00'
  },
  {
    id: 3,
    title: '《React Hooks实战视频教程》',
    summary: '从零开始学习React Hooks，通过实际项目案例深入理解useState、useEffect、useContext等重要Hooks的使用。',
    type: 'video',
    audioUrl: '',
    videoUrl: 'https://example.com/video/react-hooks.mp4',
    operator: '赵六',
    updater: '钱七',
    createTime: '2024-01-22 16:40:00',
    updateTime: '2024-01-25 11:20:00'
  },
  {
    id: 4,
    title: '《TypeScript进阶技巧》',
    summary: '深入探讨TypeScript的高级特性，包括泛型、装饰器、模块系统等，适合有一定基础的开发者学习。',
    type: 'text',
    audioUrl: '',
    videoUrl: '',
    operator: '孙八',
    updater: '周九',
    createTime: '2024-01-28 13:55:00',
    updateTime: '2024-02-01 10:10:00'
  },
  {
    id: 5,
    title: '《Node.js微服务架构音频分享》',
    summary: '通过音频形式分享Node.js微服务架构的设计理念、技术选型和实际应用经验。',
    type: 'audio',
    audioUrl: 'https://example.com/audio/nodejs-microservice.mp3',
    videoUrl: '',
    operator: '吴十',
    updater: '吴十',
    createTime: '2024-02-05 14:30:00',
    updateTime: '2024-02-05 14:30:00'
  }
]

// 获取文章列表
const fetchArticleList = async (searchParams = {}) => {
  try {
    console.log('发起文章列表请求')
    console.log('搜索参数:', searchParams)
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 模拟筛选逻辑
    let filteredData = [...mockData]
    
    if (searchParams.title) {
      filteredData = filteredData.filter(item => 
        item.title.includes(searchParams.title)
      )
    }
    
    if (searchParams.type) {
      filteredData = filteredData.filter(item => item.type === searchParams.type)
    }
    
    if (searchParams.operator) {
      filteredData = filteredData.filter(item => 
        item.operator.includes(searchParams.operator)
      )
    }
    
    // 模拟分页
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    const pageData = filteredData.slice(start, end)
    
    articles.value = pageData
    pagination.total = filteredData.length
    
    ElMessage.success(`成功获取 ${pageData.length} 条文章数据`)
    
    /* 
    // 实际API调用示例
    const params = {
      ...searchParams,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    const req = new request(api.contentUrl.articleList, params)
    const response = await req.doGet()
    
    if (response && response.code === 0) {
      articles.value = response.data?.articles || []
      pagination.total = response.data?.total || 0
      ElMessage.success(`成功获取 ${articles.value.length} 条文章数据`)
    } else {
      ElMessage.error(response?.message || '获取文章列表失败')
      articles.value = []
      pagination.total = 0
    }
    */
  } catch (error) {
    console.error('获取文章列表异常:', error)
    ElMessage.error('网络异常，请稍后重试')
    articles.value = []
    pagination.total = 0
  }
}

// 获取文章类型标签样式
const getTypeTagType = (type) => {
  const typeMap = {
    text: 'info',
    audio: 'warning',
    video: 'success'
  }
  return typeMap[type] || 'info'
}

// 获取文章类型文本
const getTypeText = (type) => {
  const typeMap = {
    text: '纯文章',
    audio: '音频文章',
    video: '视频文章'
  }
  return typeMap[type] || '未知'
}

// 预览媒体文件
const previewMedia = (url, type) => {
  console.log(`预览${type}:`, url)
  ElMessage.info(`正在打开${type === 'audio' ? '音频' : '视频'}播放器...`)
  // 这里可以实现实际的媒体预览功能
  // 比如打开新窗口或者弹出媒体播放器对话框
  window.open(url, '_blank')
}

// 构建搜索参数的通用函数
const buildSearchParams = () => {
  const searchParams = {}
  Object.keys(searchForm).forEach(key => {
    const value = searchForm[key]
    if (value !== '' && value !== null && value !== undefined) {
      if (Array.isArray(value) && value.length > 0) {
        searchParams[key] = value
      } else if (!Array.isArray(value)) {
        searchParams[key] = value
      }
    }
  })
  return searchParams
}

// 搜索处理
const handleSearch = async () => {
  try {
    const valid = await searchFormRef.value.validate()
    if (valid) {
      console.log('表单验证通过，搜索条件:', searchForm)
      
      const searchParams = buildSearchParams()
      pagination.currentPage = 1
      await fetchArticleList(searchParams)
    }
  } catch (error) {
    console.log('表单验证失败:', error)
    ElMessage.error('请检查输入内容是否正确')
  }
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  })
  
  searchFormRef.value?.clearValidate()
  pagination.currentPage = 1
  fetchArticleList()
  ElMessage.info('搜索条件已重置')
}

// 新增文章
const handleAdd = () => {
  console.log('跳转到新增文章页面')
  router.push({ name: 'contentAdd' })
}

// 编辑文章
const editArticle = (row) => {
  console.log('编辑文章:', row)
  router.push({ 
    name: 'contentEdit', 
    params: { id: row.id } 
  })
}

// 查看详情
const viewDetail = (row) => {
  console.log('查看文章详情:', row)
  ElMessage.info(`查看文章《${row.title}》的详情`)
  // 这里可以跳转到文章详情页面或者打开详情对话框
}

// 删除文章
const deleteArticle = (row) => {
  deleteDialogMessage.value = `确定要删除文章《${row.title}》吗？删除后将无法恢复。`
  currentDeleteRow.value = row
  deleteDialogVisible.value = true
}

// 处理删除确认
const handleDeleteConfirm = async () => {
  if (!currentDeleteRow.value) return
  
  try {
    console.log('确认删除文章:', currentDeleteRow.value)
    
    // 这里应该调用实际的删除文章API
    // const response = await deleteArticleAPI(currentDeleteRow.value.id)
    // if (response.code === 0) {
    //   ElMessage.success('文章删除成功')
    //   const searchParams = buildSearchParams()
    //   await fetchArticleList(searchParams)
    // } else {
    //   ElMessage.error(response.message || '删除文章失败')
    // }
    
    // 模拟删除成功
    ElMessage.success('文章删除成功')
    
    // 重新获取文章列表
    const searchParams = buildSearchParams()
    await fetchArticleList(searchParams)
    
  } catch (error) {
    console.error('删除文章异常:', error)
    ElMessage.error('删除文章失败，请稍后重试')
  } finally {
    currentDeleteRow.value = null
  }
}

// 处理删除取消
const handleDeleteCancel = () => {
  console.log('用户取消了删除文章操作')
  currentDeleteRow.value = null
  ElMessage.info('已取消删除操作')
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  console.log('每页条数变更:', val)
  
  const searchParams = buildSearchParams()
  fetchArticleList(searchParams)
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  console.log('当前页变更:', val)
  
  const searchParams = buildSearchParams()
  fetchArticleList(searchParams)
}

// 页面初始化
onMounted(() => {
  console.log('页面初始化，开始获取文章列表')
  fetchArticleList()
})
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.el-form--inline .el-form-item {
  margin-bottom: 15px;
}

.text-muted {
  color: #909399;
}
</style>
